package com.sfpay.merchant.auth.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sfpay.merchant.auth.entity.system.SysUserOnline;
import com.sfpay.merchant.auth.mapper.SysUserOnlineMapper;
import com.sfpay.merchant.auth.service.ISysUserOnlineService;
import com.sfpay.merchant.common.constant.ShiroConstants;
import com.sfpay.merchant.common.utils.StringUtils;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Deque;
import java.util.List;

/**
 * <p>
 * 在线用户记录 服务实现类
 * </p>
 *
 * @author fangchen
 * @since 2022-08-09
 */
@Service
public class SysUserOnlineServiceImpl extends ServiceImpl<SysUserOnlineMapper, SysUserOnline> implements ISysUserOnlineService {

    @Autowired
    private SysUserOnlineMapper userOnlineDao;

    @Resource
    private EhCacheManager ehCacheManager;

    @Resource
    private SysUserOnlineMapper sysUserOnlineMapper;

    @Override
    public void removeUserCache(String loginName, String sessionId) {
        Cache<String, Deque<Serializable>> cache = ehCacheManager.getCache(ShiroConstants.SYS_USERCACHE);
        Deque<Serializable> deque = cache.get(loginName);
        if (StringUtils.isEmpty(deque) || deque.size() == 0) {
            return;
        }
        deque.remove(sessionId);
    }

    @Override
    public void replaceInsert(SysUserOnline sysUserOnline) {
        sysUserOnlineMapper.replaceInsert(sysUserOnline);
    }

    /**
     * 查询会话集合
     *
     * @param userOnline 在线用户
     */
    @Override
    public List<SysUserOnline> selectUserOnlineList(SysUserOnline userOnline) {
        return userOnlineDao.selectUserOnlineList(userOnline);
    }

    @Override
    public SysUserOnline selectOnlineById(String sessionId) {
        return userOnlineDao.selectOnlineById(sessionId);
    }

    /**
     * 保存会话信息
     *
     * @param online 会话信息
     */
    @Override
    public void saveOnline(SysUserOnline online) {
        userOnlineDao.saveOnline(online);
    }
}
